<?php
class D_Adapter_Pdo
{	
	private $pdo;
	private $statment;
	private	$dbhost;
	private $username;
	private $password;
	private $dbname;
	private $charset;
	private $pconnect;
	public function __construct($dbhost, $username, $password, $dbname='',$charset='utf8', $pconnect = false)
	{
		
		 $this->dbhost = $dbhost;
		 $this->username = $username;
		 $this->password = $password;
		 $this->dbname = $dbname;
		 $this->charset = $charset;
		 $this->pconnect = $pconnect;
		
	}
	public function insert($sql, $bind=array())
	{
		 return $this->query($sql,$bind);
	}
	public function update($sql, $bind=array())
	{
	     return $this->query($sql,$bind);
	}
	public function delete($sql,$bind=array())
	{
		 return $this->query($sql,$bind);
	}
	public function fetchRow($sql, $bind=array(),$type='FETCH_ASSOC')
	{	
		if($this->query($sql,$bind))
		{
			if($type == 'FETCH_ASSOC')
			{
				 return $this->statment->fetch(PDO::FETCH_ASSOC);
				
			}
			else
			{
				 return $this->statment->fetch(PDO::FETCH_NUM);
			}
		}
	}
	public function fetchAll($sql, $bind=array(),$type='FETCH_ASSOC')
	{
		if($this->query($sql,$bind))
		{
			if($type == 'FETCH_ASSOC')
			{	
				return $this->statment->fetchAll(PDO::FETCH_ASSOC);
			}
			else
			{
				return $this->statment->fetchAll(PDO::FETCH_NUM);
			}
		}
	}
	public function query($sql, $bind=array())
	{
		
		if(empty($this->pdo))
		{
			$this->connect($this->dbhost, $this->username, $this->password, $this->dbname,$this->charset, $this->pconnect);
		}
		$this->statment = $this->pdo->prepare($sql);
		try
		{
			$state = $this->statment->execute($bind);
		}
		catch(PDOException $e)
		{
			echo "pdo execute error!";
			exit;
		}
		if(!empty($state)) 
		{
			return true;
		}
		else
		{
			L_Recover::getSql($sql);
			if(empty($query))
			{
				trigger_error("mysql query user_error!^_^", E_USER_ERROR);
			
			}
			return false;
		}
	}
	public function get_num()
	{
		$num_rows = $this->statment->rowCount();
		return $num_rows;
	}
	private function connect($dbhost, $username, $password, $dbname='',$charset='utf8', $pconnect = false)
	{
		
		
		if($pconnect)
		{
			$this->pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $username, $password);
			

			$this->pdo->exec("set names '$charset'");
			
		}
		else
		{
			$this->pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $username, $password,
								array( PDO::ATTR_PERSISTENT => true));
			//$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->pdo->exec("set names '$charset'");
			
		}
	}

}
//$x = new Pdo_Adapter("127.0.0.1","root","","shoucang1");
//
//
//$x->insert("INSERT INTO user (`username`, `email`, `user_id`) VALUES ('zhibin', 'www@126.com', '1870')
//
//");
?>